//
//  YH_AboutUsViewController.m
//  YinHang
//
//  Created by apple on 14-9-18.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_AboutUsViewController.h"
#import "YH_AboutUsTableViewCell.h"
#import "YH_ChangeAboutUsViewController.h"
@interface YH_AboutUsViewController ()<UITableViewDelegate,UITableViewDataSource,AboutUsServiceDelegate,ASIHTTPRequestDelegate>
{
    UIBarButtonItem *editButton;
    UITableViewCell *cell;

    NSMutableArray *_dataMArr; //后台数据
    
    AboutUsDataSource *DataSource;
    NSInteger selectRow;
    
    ASIFormDataRequest *delRequest_;//删除请求
}

@end

@implementation YH_AboutUsViewController

-(void)didSaveData:(AboutUs *)_AboutUs{
    if ([_dataMArr containsObject:_AboutUs]) { //处理更新操作
        [_tableView reloadData];
    } else { //处理增加操作
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_dataMArr.count - 1 inSection:0];
        [_dataMArr insertObject:_AboutUs atIndex:_dataMArr.count - 1];
        [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}
-(void)dealloc{
    DataSource = nil;
    [delRequest_ cancel];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title = @"关于我们";
   
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    

    
   [self setUI];
   UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    addBtn.frame = CGRectMake(0, 0, 60, 35);
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addBtn setTintColor:[UIColor whiteColor]];
    [addBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    addBtn.titleLabel.textColor = [UIColor whiteColor];
    [addBtn addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
   //editButton = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleBordered target:self action:@selector(editAction)];
   //[editButton setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    
    editButton = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
    editButton.tintColor=[UIColor whiteColor];
    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,editButton];
    }else{
        self.navigationItem.rightBarButtonItems = @[editButton];
    }
 
    
   _dataMArr=[self buildDataSource];
}
    
    
-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
   

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setUI{
        //加载TableView
    _tableView =[[UITableView alloc]initWithFrame:(IPHONE5? CGRectMake(self.view.frame.origin.x+10, self.view.frame.origin.y, self.view.frame.size.width-20, self.view.frame.size.height-64):CGRectMake(self.view.frame.origin.x+10, self.view.frame.origin.y, self.view.frame.size.width-20, self.view.frame.size.height-152))];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    
    _tableView.backgroundColor=[UIColor clearColor];
  
       
    _tableView.rowHeight=70;
    if(MAIN_VERSION >= 7){
    //加长分割线
    UIEdgeInsets edgeInset = _tableView.separatorInset;
    _tableView.separatorInset = UIEdgeInsetsMake(edgeInset.top, 0, edgeInset.bottom, edgeInset.right);
    }
    //隐藏多余分割线
    
    [self setExtraCellLineHidden:_tableView];
    

    [self.view addSubview:_tableView];
    //刷新
    [self setupRefresh];
    [_tableView headerBeginRefreshing];

    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    

}
#pragma mark - Custom Method

//获取并生成数据源
- (NSMutableArray *)buildDataSource {
    
    //获取源数据
    DataSource = [[AboutUsDataSource alloc]init];
    DataSource.delegate = self;
    [DataSource pageQuery];
    return DataSource.pageInfo.dataArr;//[DataSource.aboutUsArray mutableCopy];
}

// 返回
- (void)back {
    DataSource = nil;
    [delRequest_ cancel];
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UITableview/DataSource Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (DataSource.pageInfo.dataArr.count != 0) {
        return DataSource.pageInfo.dataArr.count;
    }else{
        return 0;
    }
    //return  _dataMArr.count;
    //return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 
    static NSString *cellId = @"YH_AboutUsTableViewCell";
    
    cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"YH_AboutUsTableViewCell" owner:nil options:nil][0];
        
    }
 
    NSUInteger row = [indexPath row];
    //id obj =_dataMArr[row];

    UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:2];
    UIImageView *imageView=(UIImageView *)[cell.contentView viewWithTag:3];
    /*
    if ([obj isKindOfClass:[AboutUs class]]) {
        AboutUs *aboutus=(AboutUs *)obj;
        label1.text=aboutus.titleStr;
        label2.text=aboutus.contentStr;
        imageView.image=[UIImage imageNamed:@"MJs3.png"];
        cell.textLabel.text = nil;
    } else {
        label1.text=nil;
        label2.text=nil;
        imageView.image=nil;
        cell.textLabel.text = obj;
    }*/
    label1.text = DataSource.pageInfo.dataArr[row][@"title"];
    label2.text = DataSource.pageInfo.dataArr[row][@"linkurl"];
    imageView.image=[UIImage imageNamed:@"u16.png"];
    UIButton *alertBtn = (UIButton *)[cell.contentView viewWithTag:10];
    [alertBtn addTarget:self action:@selector(alert:) forControlEvents:UIControlEventTouchUpInside];
    alertBtn.tag = row + 100;
    UIButton *deleteBtn = (UIButton *)[cell.contentView viewWithTag:11];
    [deleteBtn addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    deleteBtn.tag = row + 200;
    
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 70;


}

- (void)setExtraCellLineHidden: (UITableView *)tableView

{
    
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
   
    
}

//实现Cell的滑动删除， 需要实现UITableView的代理UITableViewDelegate中如下方法：

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableView.editing && indexPath.row == _dataMArr.count - 1) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleInsert) {
        
        YH_ChangeAboutUsViewController *cau_VC = [[YH_ChangeAboutUsViewController alloc]initWithNibName:@"YH_ChangeAboutUsViewController" bundle:nil];
        cau_VC.state = @"添加";
        cau_VC.delegate=self;
        
       //cau_VC.YH_auVC=self;
        [self.navigationController pushViewController:cau_VC animated:YES];
        
        
        
    }else if (editingStyle==UITableViewCellEditingStyleDelete)
    {
    
        [DataSource.pageInfo.dataArr removeObjectAtIndex:indexPath.row];
        //[label2Array removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [_tableView reloadData];
        
   }
}
//以下方法可以不是必须要实现，添加如下方法可实现特定效果：

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//实现Cell可上下移动，调换位置，需要实现UiTableViewDelegate中如下方法：

//先设置Cell可移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataMArr.count - 1) {
        return YES;
    }
    return NO;
    
}

//当两个Cell对换位置后
- (void)tableView:(UITableView*)tableView moveRowAtIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
 
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//限制可以交换的行数
- (NSIndexPath*)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath{
    
    if (proposedDestinationIndexPath.row == _dataMArr.count - 1) {
        return sourceIndexPath;
    }
    return proposedDestinationIndexPath;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


 
    indexPath = [tableView indexPathForSelectedRow];
    
    YH_ChangeAboutUsViewController *cau_VC=[[YH_ChangeAboutUsViewController alloc]initWithNibName:@"YH_ChangeAboutUsViewController" bundle:nil];
    cau_VC.TitleStr = DataSource.pageInfo.dataArr[indexPath.row][@"title"];
    cau_VC.ContentStr = DataSource.pageInfo.dataArr[indexPath.row][@"linkurl"];
    cau_VC.state = @"修改";
    cau_VC.delegate=self;
    cau_VC.selectId = DataSource.pageInfo.dataArr[indexPath.row][@"id"];
    cell = [_tableView cellForRowAtIndexPath:indexPath];
    
    //cau_VC.aboutus = _dataMArr[indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:cau_VC animated:YES];
    

}

//添加
- (void)editAction{
    /*
    if ([editButton.title isEqualToString:@"编辑"]) {
        [editButton setTitle:@"确定"];
        //[editButton setStyle:UIBarButtonItemStyleBordered];
        [self setEditing:YES animated:YES];
        
        
    }else {
        [editButton setTitle:@"编辑"];
        //[editButton setStyle:UIBarButtonItemStylePlain];
        [self setEditing:NO animated:YES];
    }*/
    YH_ChangeAboutUsViewController *cau_VC = [[YH_ChangeAboutUsViewController alloc]initWithNibName:@"YH_ChangeAboutUsViewController" bundle:nil];
    cau_VC.state = @"添加";
    cau_VC.delegate=self;
    
    //cau_VC.YH_auVC=self;
    [self.navigationController pushViewController:cau_VC animated:YES];

}

#pragma mark - Override Inherited Method

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    if (editing) {
      
            
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:DataSource.pageInfo.dataArr.count inSection:0];
    [DataSource.pageInfo.dataArr addObject:@"添加Book"];
        
    [_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_dataMArr.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

    }
    else{
    
        if ([[DataSource.pageInfo.dataArr lastObject]isKindOfClass:[NSString class]]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:DataSource.pageInfo.dataArr.count - 1 inSection:0];
            [DataSource.pageInfo.dataArr removeLastObject];
            [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
        }
    }
    [_tableView setEditing:editing animated:animated];

    [super setEditing:editing animated:animated];
  
}

#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (DataSource.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    DataSource.pageInfo.pageno = @"1";
    [DataSource pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (DataSource.isQuery || !DataSource.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        DataSource.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [DataSource.pageInfo nextPage];
    [DataSource pageQuery];
}

- (void)didSaveData{
    // 每次必须重置下 否则会数据混乱
    DataSource.pageInfo.pageno = @"1";
    [DataSource pageQuery];
    [_tableView reloadData];
}
#pragma mark IBAction Methods
//修改
-(void)alert:(id)sender{
    UIButton *btn = sender;
    
    selectRow = btn.tag - 100;
    YH_ChangeAboutUsViewController *cau_VC=[[YH_ChangeAboutUsViewController alloc]initWithNibName:@"YH_ChangeAboutUsViewController" bundle:nil];
    cau_VC.TitleStr = DataSource.pageInfo.dataArr[selectRow][@"title"];
    cau_VC.ContentStr = DataSource.pageInfo.dataArr[selectRow][@"linkurl"];
    cau_VC.state = @"修改";
    cau_VC.selectId = DataSource.pageInfo.dataArr[selectRow][@"id"];
    cau_VC.delegate=self;
    [self.navigationController pushViewController:cau_VC animated:YES];
}
//删除
-(void)deleteBtn:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    selectRow = btn.tag - 200;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // [linkarr removeObjectAtIndex:btnTag];
        /* 请求服务器删除对应类别下的信息 */
        
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            delRequest_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            delRequest_.requestMethod = @"POST";
            // 设置超时时间
            delRequest_.timeOutSeconds = 30;
            delRequest_.delegate = self;
            // 设置参数
            NSString *action = @"aboutdel";
            NSDictionary *paramsDict =  @{@"id":DataSource.pageInfo.dataArr[selectRow][@"id"], @"uid": UNAME};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            delRequest_.postBody = [paramsData mutableCopy];
            
            [delRequest_ startAsynchronous];
        }
        
        [_tableView reloadData];
    }
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [DataSource.pageInfo.dataArr removeObjectAtIndex:selectRow];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:selectRow inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_tableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


@end
